package main

import (
	"flag"
	"net/http"
	"translate_backend/AppCommon"
	"translate_backend/AppConfig"
	"translate_backend/controllers"
	"translate_backend/db"

	//"fmt"
	"os"

	"github.com/gin-gonic/gin"
)

var (
	//配置文件
	confFile = flag.String("config", "./conf.json", "config file")

	//导出目录路径
	exportDir = flag.String("export", "./export", "export dir")
)

func main() {

	flag.Parse()

	//读取参数
	AppConfig.Conf = AppConfig.LoadAppConfig(*confFile)
	AppConfig.ExportDir = *exportDir

	//设置公共变量
	AppCommon.SetUp()

	// fmt.Println("confFile: ", AppConfig.Conf )
	// fmt.Println("exportDir: ", AppConfig.ExportDir)

	//如果是生产环境
	if AppConfig.Conf.Env == "prod" {
		gin.SetMode(gin.ReleaseMode)
	}

	//连接mongodb
	db.Connect()

	//初始化默认数据
	AppCommon.InitDataCheck()

	//导入数据
	//bc.ImportData()

	r := gin.Default()
	//允许本机跨域
	// r.Use(cors.New(cors.Config{
	// 	AllowOrigins:     []string{"http://localhost"},
	// 	AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
	// 	AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
	// 	ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
	// 	AllowCredentials: true,
	// 	// AllowOriginFunc: func(origin string) bool {
	// 	// 	return origin == "https://github.com"
	// 	// },
	// 	//MaxAge: 12 * time.Hour,
	// }))

	//允许所有跨域
	/*
		config := cors.DefaultConfig()
		//config.AllowOrigins = []string{"http://127.0.0.1"}
		config.AllowHeaders = []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type", "Content-Length"} //这里应该用拦截器做自适应
		config.ExposeHeaders = []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type", "Content-Length"}
		config.AllowAllOrigins = true
		config.AllowCredentials = true //明确许可客户端发送Cookie，不允许删除字段即可
		config.AllowMethods = []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}
		r.Use(cors.New(config))
	*/
	r.Use(Cors())

	//开启静态目录
	r.Static("/export", AppConfig.ExportDir)
	//---------路由-----------

	// Simple group: v1
	api := r.Group("/api")
	{
		//==========用户==========
		var signCon = controllers.SignCon{}
		api.GET("/userList", signCon.GetUserList)
		api.POST("/adminLogin", signCon.AdminLogin)
		api.POST("/userUpdate", signCon.Update)
		api.POST("/userDelete", signCon.Delete)
		api.POST("/userCreate", signCon.Create)

		//==========langItem==========
		var langCon = controllers.LangCon{}
		api.GET("/langItem/:id", langCon.GetLangItemDetail)
		api.GET("/langItemList", langCon.GetLangItems) // *projID ,keyword, page, pagesize
		api.POST("/langItemUpdate", langCon.Update)
		api.POST("/langItemDelete", langCon.Delete)
		api.POST("/langItemCreate", langCon.Create)

		api.GET("/exportLang/:platform", langCon.ExportLangFile) // iOS , android 旧版

		api.POST("/exportLangItems/:platform/:projID", langCon.ExportLangItems) // iOS , android 新版

		//==========项目==========
		var projCon = controllers.ProjCon{}
		api.GET("/projList", projCon.GetProjList)
		api.POST("/projUpdate", projCon.Update)
		api.POST("/projDelete", projCon.Delete)
		api.POST("/projCreate", projCon.Create)

		//==========其他==========
		//排序 general/sort"

		//初始化全部翻译(从json文件): http://localhost:8083/api/importNewJson

		//导入新增翻译(zlsftq.xlsx): http://localhost:8083/api/importExcel

		//修正翻译(校对中英文): http://localhost:8083/api/updateExcel

		//测试,导出iOS多语言
		api.GET("/exportiOSJson", langCon.ExportiOSJsonFile)

		//导入-新增本地测试文件,模板 zlsftq.xlsx
		api.GET("/importExcel", langCon.ImportLocalExcel)

		//导入-更新的测试文件,只有中英
		api.GET("/updateExcel", langCon.UpdateLocalExcel)

		//导入- 全新新增, json文件
		api.GET("/importNewJson", langCon.ImportWithJson)
	}
	//api.Use(cors.New(config))

	currentPath, _ := os.Getwd()
	println("当前目录:", currentPath)
	//--------run------
	httpport := "0.0.0.0:" + AppConfig.Conf.Httpport
	//println("httpport:", httpport)
	r.Run(httpport) // listen and serve on 0.0.0.0:8080
}

func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method

		//println("跨域处理:", method)

		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Origin, Authorization, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type, Content-Length")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
		c.Header("Access-Control-Expose-Headers", "Origin, Authorization, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type, Content-Length")
		c.Header("Access-Control-Allow-Credentials", "true")

		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			// c.JSON(http.StatusOK, "Options Request!")
			c.AbortWithStatus(http.StatusNoContent)
		}

		c.Next()
	}
}
